#!/bin/sh /etc/rc.common
#
# Copyright (C) 2015 OpenWrt-dist
# Copyright (C) 2015 Jian Chang <aa65535@live.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=90
STOP=15

CONFIG=/var/etc/shadowvpn.conf

start_vpn() {
	local enable server port password concurrency mtu intf
	config_get_bool enable $1 enable
	[ "$enable" = 1 ] || return 0
	config_get server $1 server
	config_get port $1 port
	config_get user_token $1 user_token
	config_get password $1 password
	config_get concurrency $1 concurrency
	config_get net $1 net
	config_get mtu $1 mtu
	config_get intf $1 intf
	: ${server:?}
	: ${port:?}
	: ${password:?}
	: ${user_token:=0000000000000000}
	mkdir -p $(dirname $CONFIG)
	cat <<-EOF >$CONFIG
		server=$server
		port=$port
		password=$password
		mode=client
		concurrency=1
		net=${net:-10.7.0.2/24}
		mtu=${mtu:-1432}
		intf=${intf:-tun0}
		up=/etc/shadowvpn/client_up.sh
		down=/etc/shadowvpn/client_down.sh
		pidfile=/var/run/shadowvpn.pid
		logfile=/var/log/shadowvpn.log
EOF
	if [ "$user_token" != "0000000000000000" ]; then
		echo "user_token=$user_token" >>$CONFIG
	fi
	/usr/bin/shadowvpn -c $CONFIG -s start
}

start() {
	config_load shadowvpn
	config_foreach start_vpn shadowvpn
}

stop() {
	/usr/bin/shadowvpn -c $CONFIG -s stop
}

boot() {
	if [ ! -c "/dev/net/tun" ]; then
		mkdir -p /dev/net
		mknod /dev/net/tun c 10 200
		chmod 0666 /dev/net/tun
	fi
	until ip route show 0/0 | grep -q "^default"; do
		sleep 1
	done
	start
}
